<!-- 商品详情页面组件
 -->
<template>
  <div id="details">
    <!-- 头部 -->
    <div class="page-header">
      <div class="title">
        <p>{{productDetails.spuName}}</p>
      </div>
    </div>
    <!-- 头部END -->
    <!-- 主要内容 -->
    <div class="main">
      <!-- 左侧商品轮播图 -->
      <div class="block">
        <el-carousel height="560px">
          <el-carousel-item v-for="item in productDetails.images" :key="item">
            <img style="height:100%;width:100%;" :src="item"  />
          </el-carousel-item>
        </el-carousel>
      </div>
      <!-- 左侧商品轮播图END -->

      <!-- 右侧内容区 -->
      <div class="content">
        <h1 class="name" v-show="skuVisible">{{productDetails.spuName}}</h1>
        <h1 class="name" v-show="!skuVisible">{{cartInfo.skuName}}</h1>
        <p class="intro" >简单介绍：{{productDetails.spuDescription}}</p>
        <div class="price">
          <span>品牌：{{productDetails.brandName}}</span>
        </div>
        <div class="pro-list">
          <div v-for="item in skuAttr" :key="item.attrId"> {{ item.attrName }}：
            <el-radio-group v-model="item.vallue" size="small" @change="getSkuValue">
                <el-radio-button
                  ref="rabutton"
                  :label="item"
                  v-for="(item, i) in item.attrValue"
                  :key="i"
                ></el-radio-button>
              </el-radio-group>
          </div>
             
          <span class="pro-price">
            &nbsp;&nbsp;
          <span v-show="!skuVisible">已售 {{cartInfo.saleCount}} 件</span>
          </span>
          <p ></p>
          <p class="price-sum" v-show="skuVisible">售价 : {{productDetails.price}}元</p>
          <p class="price-sum" v-show="!skuVisible">售价 : {{cartInfo.price}}元</p>
        </div>
        <div class="nunu">
          <span>数量：</span>
         <div class="number"> 
                <el-button
                  class="num-sub"
                  size="mini"
                  :disabled="number <= 1 ? true : false"
                  @click="number--"
                  icon="el-icon-minus"
                ></el-button>
                <span class="num">{{ number }}</span>
                <el-button
                  icon="el-icon-plus"
                  class="num-add"
                  size="mini"
                  :disabled="number >= cartInfo.stockCount ? true : false"
                  @click="number++"
                ></el-button>
              </div>
        </div>
        
        <!-- 内容区底部按钮 -->
        <div class="button">
          <el-button class="shop-cart" :disabled="dis" @click="addShoppingCart">加入购物车</el-button>
          <el-button class="like" @click="addCollect">喜欢</el-button>
        </div>
        <!-- 内容区底部按钮END -->
        <div class="pro-policy">
          <ul>
            <li>
              <i class="el-icon-circle-check"></i> 7天无理由退货
            </li>
            <li> 
              <i class="el-icon-circle-check"></i> 7天价格保护
            </li>
          </ul>
        </div>
      </div>
      <!-- 右侧内容区END -->
    </div>
    <!-- 主要内容END -->
    <!-- 评论内容开始 -->
    <div class="comment">
      <el-row>
        <div  class="goodsparams">
          <h3 class="showPrams">规格参数 </h3>
            <!-- 遍历属性,每个tab-pane对应一个表单，每个属性是一个表单项  baseAttrs[0] = [{attrId:xx,val:}]-->
            <div class="groupAttr" v-for="(item1,index) in  attrInfos" :key="index">
            <p class="attrName">{{item1.attrName}}:{{item1.attrValue}}</p>  
            </div>
        </div>
        <div  class="goodsdetails">
          <h3>商品详情</h3> 
          <div class="img" v-for="item in productDetails.decript" :key="item">
            <img style="height:100%;width:100%;" :src="item"  alt="" />
          </div>
           </div>
      </el-row>
      <Comment  ></Comment>
    </div>
  </div>
</template>
<script>
import { mapActions } from "vuex";
import Comment  from "../components/Comment"
import cookie from 'js-cookie'
export default {
  data() {
    return {
      dis: false, // 控制“加入购物车按钮是否可用”
      productID: "", // 商品id
      // 商品详细信息
      productDetails: {}, 
        productPicture: [
        {id: 1,
        intro: null,
        product_id: 1,
        product_picture: "https://img.alicdn.com/imgextra/i1/642496034/O1CN01lubZVf1uRcbJY2b7i_!!642496034.jpg_430x430q90.jpg"},
        {id: 2,
        intro: null,
        product_id: 1,
        product_picture: "https://img.alicdn.com/imgextra/i1/642496034/O1CN01lubZVf1uRcbJY2b7i_!!642496034.jpg_430x430q90.jpg"},
        {id: 3,
        intro: null,
        product_id: 1,
        product_picture: "https://img.alicdn.com/imgextra/i1/642496034/O1CN01lubZVf1uRcbJY2b7i_!!642496034.jpg_430x430q90.jpg"},
        {id: 4,
        intro: null,
        product_id: 1,
        product_picture: "https://img.alicdn.com/imgextra/i1/642496034/O1CN01lubZVf1uRcbJY2b7i_!!642496034.jpg_430x430q90.jpg"},
        {id: 5,
        intro: null,
        product_id: 1,
        product_picture: "https://img.alicdn.com/imgextra/i1/642496034/O1CN01lubZVf1uRcbJY2b7i_!!642496034.jpg_430x430q90.jpg"}],
        // 商品图片
        // sku参数信息
        skuAttr:[],
        // 商品sku信息
        skuInfo:[],
        // 选中的sku
        selectSku:[],
        // 选中是sku名
        str:'',
        // 加入购物车的信息
        cartInfo:{
          count:1
        },
        // 数量
        number:1,
        // 是否选中sku信息
        skuVisible:true,
        // 所有的属性信息
        attrInfos:[],
        // 所有属性值id
        attrIds:[],
        // 对应的分组名
        attrGroupName:[],
        attrGroups:[],
    };
  },
  components:{
    Comment
  },
  // 通过路由获取商品id
  activated() {
    if (this.$route.query.productID != undefined) {
      this.productID = this.$route.query.productID;
    }
  },
  watch: {
    // 监听商品id的变化，请求后端获取商品数据
    productID: function(val) {
      //  console.log("productID", this.productID)
      this.getDetails(val);
      // this.getDetailsPicture(val);
    },
    cartInfo: {
      handler(newName) {
        // console.log("new", newName, );
        this.cartInfo = newName;
        if (this.cartInfo.skuName) {
          this.skuVisible = false;
        }
      },
      immediate: true,
      deep: true,
    },
  },
  methods: {
    ...mapActions(["unshiftShoppingCart", "addShoppingCartNum"]),
    // 获取商品详细信息  
    async getDetails(val) {
      const { data: res } = await this.$http.get(`/xuanmall/spumessage/info/${val}`);
      // this.productDetails = {};
      this.cartInfo = {};
      this.catelogId = res.spuSaveVo.catalogId
      console.log("details",res);
      // 取所有属性id
      if(res.code === 0){
        this.attrInfos = res.spuSaveVo.baseAttrs
        // this.attrIds= [] 
        // res.spuSaveVo.baseAttrs.forEach(item1 =>{
        //   this.attrIds.push(item1.attrId)
        // })
        // this.attrInfos =[]
        // this.attrGroupName=[]
        // console.log(this.attrIds)
        // // if(this.attrIds.length>=1){ 
        // this.attrIds.forEach(async item2 =>{
        //   const {data:res1} = await this.$http.get(`/xuanmall/attr/info/${item2}`)
        //   // console.log("ss",res1)
        //   this.attrInfos.push(res1.respVo)
        //   if(res1.code === 0){
        //     this.attrGroupName.push(res1.respVo.groupName)
        //   }
        // })
        this.productDetails= res.spuSaveVo;
        console.log("s",this.productDetails)
          this.skuAttr =[]
          var data = { attrId: 0, attrName: "", value: "", attrValue: [] };
          this.productDetails.skus[0].attr.forEach((item) => {
            data = { attrId: 0, attrName: "", value: "", attrValue: [] };
            data.attrId = item.attrId;
            data.attrName = item.attrName;
            data.value = item.value;
            // data1.attrValue.push(item.attrValue);
            this.skuAttr.push(data);
          });
          this.skuInfo=[],
          this.productDetails.skus.forEach((item) => {
            var data1 = {};
            data1.skuId = item.skuId;
            data1.price = item.price;
            data1.descar = item.descar;
            data1.images = item.images;
            data1.skuName = item.skuName;
            data1.stockCount = item.stockCount;
            data1.saleCount = item.saleCount;
            item.attr.forEach((item1) => {
              this.skuAttr.forEach((data2) => {
                if (item1.attrId === data2.attrId) {
                  data2.attrValue.push(item1.attrValue);
                }
              });
            });
            this.skuInfo.push(data1);
            // sku参数去重
            this.skuAttr.forEach((item) => {
            item.attrValue = Array.from(new Set(item.attrValue));
            // console.log("this.skuAttr",this.skuAttr)
            // console.log("skuInfo",this.skuInfo)
          });
        });
        }
    },
    // 监听数量按钮改变
    handleChange(){},
    // 显示规格参数
    // showPrams(){  
    //    console.log("this.attrInfos",this.attrInfos)
    //     this.attrGroupName = Array.from(new Set(this.attrGroupName));
    //     console.log("this.attrGroupName",this.attrGroupName)
    //     this.attrGroups=[]
    //     this.attrGroupName.forEach(item3 =>{
    //       var data={}
    //       data.group = item3
    //       data.attr = []
    //       this.attrInfos.forEach(item4 =>{
    //         var data1 = {}
    //         if(item3 == item4.groupName){
    //           data1.attrName = item4.attrName
    //           data1.valueSelect = item4.valueSelect
    //           data.attr.push(data1)
    //         }
    //       })
    //       this.attrGroups.push(data)
    //     })
    //     console.log("this.attrGroups", this.attrGroups)
    //   console.log("this.attrGroupName",this.attrGroupName)
    // },
    // 根据选中的sku改变数据
     getSkuValue() {
      this.selectSku = [];
      this.selectSku.push(this.productDetails.spuName);
      // console.log(this.selectSku);
      this.$refs.rabutton.forEach((item) => {
        if (item._vnode.data.class[1]) {
          // console.log("AA", item.value);
          this.selectSku.push(item.value);
        }
      });
      this.selectSku = Array.from(new Set(this.selectSku));
      // console.log(this.selectSku); 
      // console.log("this.skuInfo",this.skuInfo);
      this.str = "";
      for (var i = 0; i < this.selectSku.length; i++) {
        if (i === this.selectSku.length - 1) {
          this.str += this.selectSku[i];
        } else {
          this.str += this.selectSku[i] + " ";
        }
      }
      this.cartInfo = {};
      this.skuInfo.forEach((item) => {
        // console.log("222", item.skuName, "222");
        // console.log("dd", item.skuName == this.str);
        if (item.skuName == this.str) {
          this.cartInfo.proid = this.productDetails.id;
          this.cartInfo.skuid = item.skuId;
          this.cartInfo.count = this.number;
          this.cartInfo.saleCount = item.saleCount;
          this.cartInfo.stockCount = item.stockCount;
          this.cartInfo.price = item.price;
          this.cartInfo.skuName = item.skuName;
        }
      });
      console.log("nbvbv",this.cartInfo);
    },
    // 加入购物车
    addShoppingCart() {
      if(!this.cartInfo.skuid)return this.$message.error("请先选择商品参数")
      this.$http
        .post("/xuanmall/cart/save", [{
              skuid: this.cartInfo.skuid,
              count: this.cartInfo.count,
              spuid: this.productDetails.id,
        }])
        .then(res => {
          console.log(res)
          if(res.data.code === 20006)return this.$message.error("请您先登录")
          if(res.data.code !== 0) return this.$message.error("添加购物车失败")
          // console.log(this.cartInfo)
          //  this.unshiftShoppingCart(this.cartInfo);
           this.$message.success("添加购物车成功")
          let number= JSON.parse(cookie.get("shopcarNumber")) + 1
           cookie.set("shopcarNumber", number, {
           domain: "localhost",
          });
          this.$store.dispatch("setShopcarNumber", number);
        })
        .catch(err => {
          return Promise.reject(err);
        });
    },
    addCollect() {
      if(!this.cartInfo.skuid)return this.$message.error("请先选择商品参数")
      this.$http  
        .post(`/xuanmall/productcollect/save`,{
          spuid:this.productDetails.id,
          spuName:this.productDetails.spuName,
          skuid:this.cartInfo.skuid,
          isSku:this.productDetails.isSku,
        })
        .then(res => {
          console.log("res",res)
          if(res.data.code === 20006)return this.$message.error("请您先登录")
          if (res.data.code === 0) {
            // 添加收藏成功
            this.$message.success("添加收藏成功")
          } else {
            // 添加收藏失败
            this.$message.error("添加收藏失败")
          }
        })
        .catch(err => {
          return Promise.reject(err);
        });
    }
  }
};
</script>
<style >
/* 头部CSS */
#details .page-header {
  height: 64px;
  margin-top: -20px;
  z-index: 4;
  background: #fff;
  border-bottom: 1px solid #e0e0e0;
  -webkit-box-shadow: 0px 5px 5px rgba(0, 0, 0, 0.07);
  box-shadow: 0px 5px 5px rgba(0, 0, 0, 0.07);
}
#details .page-header .title {
  width: 1225px;
  height: 64px;
  line-height: 64px;
  font-size: 18px;
  font-weight: 400;
  color: #212121;
  margin: 0 auto;
}
#details .page-header .title p {
  float: left;
}

/* 头部CSS END */

/* 主要内容CSS */
#details .main ,.comment {
  width: 1225px;
  height: 560px;
  padding-top: 30px;
  margin: 0 auto;
}
#details .main .block {
  float: left;
  width: 500px;
  height: 560px;
  padding:  0 20px;
}
#details  .el-carousel .el-carousel__indicator .el-carousel__button {
  background-color: rgba(163, 163, 163, 0.8);
}
#details .main .content {
  float: left;
  margin-left: 25px;
  width: 640px;
}
#details .main .content .name {
  height: 30px;
  line-height: 30px;
  font-size: 24px;
  font-weight: normal;
  color: #212121;
}
#details .main .content .intro {
  color: #b0b0b0;
  padding-top: 10px;
}
#details .main .content .store {
  color: #ff6700;
  padding-top: 10px;
}
.showPrams{
  cursor: pointer;
}
#details .main .content .price {
  display: block;
  font-size: 18px;
  color: #ff6700;
  border-bottom: 1px solid #e0e0e0;
  padding: 25px 0 25px;
}
#details .main .content .price .del {
  font-size: 14px;
  margin-left: 10px;
  color: #b0b0b0;
  text-decoration: line-through;
}

#details .main .content .pro-list {
  background: #f9f9fa;
  padding: 10px 60px;
  margin: 20px 0 50px;
}
#details .main .content .pro-list div {
  line-height: 80px;
  color: #616161;
}
#details .main .content .pro-list div .el-input-number__increase .el-input-number__decrease{
  margin-top: 24px;
}
#details .main .content .pro-list span {
  line-height: 30px;
  color: #616161;
}
#details .main .content .pro-list .pro-price {
  float: right;
}
#details .main .content .pro-list .pro-price .pro-del {
  margin-left: 10px;
  text-decoration: line-through;
}
#details .main .content .pro-list .price-sum {
  color: #ff6700;
  font-size: 24px;
  padding-top: 20px;
}
#details .main .content .button {
  height: 55px;
  margin: 10px 0 20px 0;
}
#details .main .content .nunu{
  /* background-color: red; */
  margin: 0 10px 20px 10px;
  color: rgb(124, 118, 118);
  font-size: 19px;
}
#details .main .content .num {
        display: inline-block;
        width: 40px;
        height: 31px;
        border-right: 2px solid rgb(82, 79, 79);
        border-left: 2px solid rgb(82, 79, 79);
        text-align: center;
      }
 #details .main .content     .number {
        box-sizing: border-box;
        height: 35px;
        border-radius: 3px;
        display: inline-block;
        border: 2px solid rgb(80, 75, 75);
        background-color: #fff;
      }

#details .groupAttr{
  margin: 20px;
   font-weight: 300;
   font-size: 15px;
}

#details .main .content .button .el-button {
  float: left;
  height: 55px;
  font-size: 16px;
  color: #fff;
  border: none;
  text-align: center;
}
#details .main .content .button .shop-cart {
  width: 340px;
  background-color: #ff6700;
}
#details .main .content .button .shop-cart:hover {
  background-color: #f25807;
}

#details .main .content .button .like {
  width: 260px;
  margin-left: 40px;
  background-color: #b0b0b0;
}
#details .main .content .button .like:hover {
  background-color: #757575;
}
#details .img{
  text-align: center;
  height: 1000px;
  width: 800px;
}
#details .comment{
  width: 1200px;
}
#details .comment .goodsparams{
 width: 300px;
 margin: 10px 0;
display: inline-block;
}
#details .comment .goodsdetails{
  width: 900px;
 float: right;
}
#details .main .content .pro-policy li {
  float: left;
  margin-right: 20px;
  color: #b0b0b0;
  margin-bottom: 20px;
}
/* 主要内容CSS END */
</style>